package cn.mumzone.pos.ui.fragment.bills;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.net.response.PageListResponse;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.ui.activity.ACT_BillReturn;
import cn.mumzone.pos.model.BillDetailEntity;
import cn.mumzone.pos.ui.adapter.ADA_BillItemList;
import cn.mumzone.pos.model.BillInfoListBean;
import cn.mumzone.pos.presenter.BillsItemPresenter;
import cn.mumzone.pos.presenter.contract.BillsItemContract;
import cn.mumzone.pos.ui.activity.ACT_BillGoodsDetail;
import cn.mumzone.pos.ui.widgets.refresh.SmartRefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.constant.RefreshState;
import cn.mumzone.pos.util.BillUtil;
import cn.mumzone.pos.util.print.PrinterService;
import cn.mumzone.pos.ui.widgets.refresh.api.RefreshLayout;

/**
 * Created By Dlx
 * on 2019/6/22
 */
public class FRA_BillItem extends BaseFragment<BillsItemPresenter> implements BillsItemContract.View, OnLoadMoreListener {

    public static final int GOODS = 1;
    public static final int SERVICE = 0;
    public static final int INTEGRAL_GOODS = 3;

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.billitem_recyclerview)
    LRecyclerView recycler;
    @BindView(R.id.ll_bill_list)
    LinearLayout llBillList;

    @BindView(R.id.ll_root)
    LinearLayout rootLayout;
    private LRecyclerViewAdapter lRecyclerViewAdapter = null;
    private ADA_BillItemList adapter;
    private int type;
    private int pageNum = 1;
    private List<BillInfoListBean> datas = new ArrayList<>();
    private boolean isSearch = false;
    private String searchKey;
    private boolean isNoMore = false;
    private TextView headerTitle, headerContent;
    private boolean isShowError = false;
    private boolean isShowNetWorkError = false;

    private BillInfoListBean mClickedEntity;

    private long dateTime;

    public static FRA_BillItem newInstance(int type) {
        FRA_BillItem fra = new FRA_BillItem();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fra.setArguments(bundle);
        return fra;
    }


    @Override
    protected void onUserVisible() {
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        type = extras.getInt("type", -1);
        dateTime = System.currentTimeMillis();
    }

    @Override
    protected void initEventAndData() {


        mPresenter.initEvent();
        final GridLayoutManager manager = new GridLayoutManager(mContext, 4);
        recycler.setLayoutManager(manager);
        adapter = new ADA_BillItemList(getActivity(), type);
        adapter.setClickListener(new ADA_BillItemList.BillOnClickListener() {
            @Override
            public void onCardClick(String saleId, String orderType) {
                ACT_BillGoodsDetail.startAct(mContext, saleId, Integer.parseInt(orderType));
            }

            @Override
            public void onPrintClick(String saleId, String orderType) {
                mPresenter.getGoodsBillDetailForPrint(saleId, orderType);
            }

            @Override
            public void onReturnClick(BillInfoListBean billInfoListBean) {
                mClickedEntity = billInfoListBean;
                ACT_BillReturn.startActForResult(getActivity(), billInfoListBean.getSaleId(), billInfoListBean.getOrderType(),
                        billInfoListBean.getOrderCode(), true, ACT_BillReturn.REQUEST_CODE_FOR_RETURN);
            }
        });
        lRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);

        View header = LayoutInflater.from(getActivity()).inflate(R.layout.header_bill, null);
        headerTitle = header.findViewById(R.id.header_title);
        headerContent = header.findViewById(R.id.header_content);
        lRecyclerViewAdapter.addHeaderView(header);
        recycler.setAdapter(lRecyclerViewAdapter);
        GridItemDecoration divider = new GridItemDecoration.Builder(mContext)
                .setHorizontal(R.dimen.default_divider_padding)
                .setColorResource(android.R.color.transparent)
                .build();
        recycler.addItemDecoration(divider);
        recycler.setHasFixedSize(true);
        recycler.setPullRefreshEnabled(false);
        recycler.setOnLoadMoreListener(this);

        refreshLayout.setOnRefreshListener(new cn.mumzone.pos.ui.widgets.refresh.listener.OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNum = 1;
                mPresenter.getBillDatas(AppDateUtil.getTimeStamp(dateTime, AppDateUtil.YYYY_MM_DD), type, searchKey, pageNum);

            }
        });

        refreshLayout.autoRefresh();

    }

    @Override
    protected View getTargetView() {
        return llBillList;
    }

    @Override
    public void showError(String msg) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        isShowError = true;
        toggleShowEmpty(true, R.mipmap.ic_bill_empty, type == SERVICE ? "暂无服务单" : "暂无商品单", "美好的一天，从开启第一单开始~");
    }


    @Override
    public void showNetError() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        isShowNetWorkError = true;
        showNetErrorEmpty(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FRA_BillItem.super.toggleCloseEmpty();
                refreshLayout.autoRefresh();
            }
        });
    }

    private void switchHeaderStatus(boolean isSearch) {
        if (isSearch) {
            setViewVisibility(headerContent, false);
            headerTitle.setText("搜索结果");
        } else {
            setViewVisibility(headerContent, true);
            headerTitle.setText("今日账单");
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.fra_billitem;
    }

    @Override
    public void onDataReceived(PageListResponse<BillInfoListBean> data, boolean refresh) {

        toggleShowEmpty(false);

        if (refresh) {
            datas.clear();
            datas.addAll(data.getList());
            adapter.setDatas(datas, refresh);
        } else {
            datas.addAll(data.getList());
            adapter.setDatas(datas, refresh);
        }
        lRecyclerViewAdapter.notifyDataSetChanged();

        refreshLayout.finishRefresh();

    }

    @Override
    public void onSearchDataReceived(PageListResponse<BillInfoListBean> data, boolean refresh) {

        toggleShowEmpty(false);

        if (refresh) {
            datas.clear();
            datas.addAll(data.getList());
            adapter.setDatas(datas, refresh);
            adapter.notifyDataSetChanged();
        } else {
            datas.addAll(data.getList());
            adapter.setDatas(datas, refresh);
        }
        lRecyclerViewAdapter.notifyDataSetChanged();

        refreshLayout.finishRefresh();

    }

    @Override
    public void onPrintDataReceived(BillDetailEntity billDetailEntity) {
        PrinterService.doPrintTicket(mContext, BillUtil.generatePrintEntity(billDetailEntity), 1);
    }

    @Override
    public void showToast(String str) {

    }

    @Override
    public void onNoMore(boolean tof) {
        isNoMore = tof;
        recycler.setNoMore(tof);
        recycler.refreshComplete(AppConstants.PAGE_SIZE);
    }

    @Override
    public void onSearchEvent(String searchKey) {
        pageNum = 1;
        isSearch = !StringUtils.isEmpty(searchKey);
        this.searchKey = searchKey;
        switchHeaderStatus(isSearch);

        toggleCloseEmpty();
        refreshLayout.autoRefresh();

    }

    @Override
    public void noSuchSearchResult() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        toggleShowEmpty(true, R.mipmap.ic_bill_empty, "没有找到任何内容", "你可以换个关键词试试~");
    }

    @Override
    public void onLoadMore() {
        if (isNoMore) {
            recycler.setNoMore(true);
            recycler.refreshComplete(AppConstants.PAGE_SIZE);
            return;
        }
        pageNum++;
        mPresenter.getBillDatas(AppDateUtil.getTimeStamp(dateTime, AppDateUtil.YYYY_MM_DD), type, searchKey, pageNum);

    }

    private void refreshBillData() {
        refreshLayout.autoRefresh();
    }

    public void setDateTime(long dateTime) {
        this.dateTime = dateTime;
        refreshBillData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (type != GOODS) {
            return;
        }

        if (requestCode == ACT_BillReturn.REQUEST_CODE_FOR_RETURN) {
            if (resultCode == Activity.RESULT_OK) {
                refreshBillData();
            }
//            else if (resultCode == Activity.RESULT_FIRST_USER) {
//                ACT_BillGoodsDetail.startAct(mContext, mClickedEntity.getSaleId(), Integer.parseInt(mClickedEntity.getOrderType()));
//            }
        }
    }

    public boolean isRefreshing() {
        return refreshLayout.getState() != RefreshState.None;
    }

}
